<template>
  <!-- 手动创建订单 销售订单-->
  <el-dialog :title="title" :visible.sync="dialogVisible" :close-on-click-modal="false" @close="reset" width="980px">
    <div class="form-box new_form_box">
      <el-form ref="form" :model="form" :inline="true" :rules="rules" label-width="80px" class="demo-ruleForm">
        <div style="margin-bottom: 10px;">
          <formSubTitVue title="订单信息"></formSubTitVue>
        </div>
        <el-form-item label="销售人" prop="saleUserId">
          <el-select filterable clearable v-model="form.saleUserId" placeholder="请选择销售人" @change="buyerChange">
            <el-option v-for="(item ,key) in yuangongList" :key="key" :label="item.nickName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="销售渠道" prop="saleChannel">
          <el-input v-show="false" v-model="form.saleChannel" placeholder="请输入" />
          <span class="phone-box flex">
            <span class="name" v-if="form.saleChannel">{{ form.saleChannel }}</span>
            <el-button type="text" @click="openSelectQudao(2)">
              选择
            </el-button>
            <el-button v-if="form.saleChannel" type="del" @click="delPhone('saleChannel')">
              清空
            </el-button>
          </span>
        </el-form-item>
        <el-form-item label="三方单号" prop="otherNo">
          <el-input v-model="form.otherNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="供货商" prop="supplyChannel" v-if="!isEdit||(isEdit&&form.sourceScen!=4)">
          <el-input v-show="false" v-model="form.supplyChannel" placeholder="请输入" />
          <span class="phone-box flex">
            <span class="name" v-if="form.supplyChannel">{{ form.supplyChannel }}</span>
            <el-button type="text" @click="openSelectQudao(3)">
              选择
            </el-button>
            <el-button v-if="form.supplyChannel" type="del" @click="delPhone('supplyChannel')">
              清空
            </el-button>
          </span>
        </el-form-item>
        <!-- <br/> -->
        <!-- <el-form-item label="买家名称" prop="sellerName">
          <el-input v-model="form.sellerName" placeholder="请输入买家名称" />
        </el-form-item> -->
        <el-form-item label="游戏名称" prop="gameId">
          <el-select  filterable v-model="form.gameId" placeholder="请选择游戏名称" @change="gameChange">
            <el-option v-for="dict in gameList" :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="游戏区服" prop="qufuIds">
          <el-cascader clearable v-model="form.qufuIds" :options="qufuTree" :props="qufuProps" @change="qufuChange"></el-cascader>
        </el-form-item>
        <el-form-item label="游戏账号" prop="accountNumber">
          <el-input v-model="form.accountNumber" placeholder="请输入游戏账号" />
        </el-form-item>
        <!-- <el-form-item label="账号密码" prop="accountPassword">
          <el-input v-model="form.accountPassword" placeholder="请输入账号密码" />
        </el-form-item> -->

        <!-- <el-form-item label="原手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入原手机号" />
        </el-form-item> -->

        <el-form-item label="出售价" prop="saleAmount">
          <el-input v-model="form.saleAmount" placeholder="请输入出售价" @change="computedBuyerActualAmount" />
        </el-form-item>
        <el-form-item label="包赔费" prop="guaranteeAmount">
          <el-input v-model="form.guaranteeAmount" placeholder="请输入包赔费" @change="computedBuyerActualAmount" />
        </el-form-item>
        <!-- <el-form-item label="订单金额" prop="actualAmount" @change="computedBuyerActualAmount">
          <el-input v-model="form.actualAmount" placeholder="请输入订单金额" />
        </el-form-item> -->
        <el-form-item label="成本" prop="supplyAmount">
          <el-input :disabled="isEdit" v-model="form.supplyAmount" placeholder="请输入回收价" @change="computedBuyerActualAmount" />
        </el-form-item>
        <!--
        <el-form-item label="包赔费" prop="guaranteeAmount">
          <el-input v-model="form.guaranteeAmount" placeholder="请输入包赔费" @change="computedBuyerActualAmount" />
        </el-form-item> -->

        <el-form-item label="支付状态" prop="salePay">
          <el-select v-model="form.salePay" placeholder="请选择支付状态">
            <el-option label="未支付" :value="1" />
            <el-option label="已支付" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="换绑状态" prop="changePhoneState">
          <el-select v-model="form.changePhoneState" placeholder="请选择换绑状态">
            <el-option label="未换绑" :value="1" />
            <el-option label="已换绑" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="换绑手机" prop="changeTel">
          <el-input v-model="form.changeTel" placeholder="请输入换绑手机号" />
        </el-form-item>
        <div v-if="form.actualAmount" style="text-align: right;padding-right: 40px;padding-bottom: 10px;">
          <span class="font16">订单金额：</span>
          <span style="color: red;font-size: 24px;">{{ form.actualAmount }}</span>
        </div>
        <el-form-item label="" prop="" class="row">
          <div class="upload_img_box flex">
            <el-form-item label="换绑截图" prop="changePhoneImg">
              <uploadImageOne v-model="form.changePhoneImg" @change="uploadSucccess($event,'changePhoneImg')"></uploadImageOne>
            </el-form-item>
            <el-form-item label="订单截图" prop="orderImg">
              <uploadImageOne v-model="form.orderImg" @change="uploadSucccess($event,'orderImg')"></uploadImageOne>
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item label="其他图片" class="row">
          <el-upload :action="uploadImgUrl" :file-list="imgShowList" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-exceed="uploadNumber" :multiple="true" :drag="true" :on-success="handleUploadSuccess" :limit="50" :on-remove="handleRemove" :headers="headers">
            <div class="uploadbg">
              <img src="https://imgage.maimaihao.com/yuduhulian/erp/static/icon/uploadbg.png" alt="">
              <br />
              <span>上传图片</span>
            </div>
          </el-upload>
          <div style="width: 100px;">
            <saomaUpload @success="saomaEnd">
              <el-button type="primary" plain>扫码上传</el-button>
            </saomaUpload>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark" class="row">
          <el-input v-model="form.remark" type="textarea" placeholder="订单备注" :rows="4" />
        </el-form-item>
        
        <div style="margin: 10px 0;">
          <formSubTitVue title="财务信息"></formSubTitVue>
        </div>
        <el-form-item label="收款方" prop="shoukuanfang">
          <el-input v-model="form.shoukuanfang" placeholder="请输入收款方" />
        </el-form-item>
        <el-form-item label="收款账号" prop="shoukuanzhanghao">
          <el-input v-model="form.shoukuanzhanghao" placeholder="请输入收款账号" />
        </el-form-item>

        <!-- <div style="margin: 10px 0;">
          <formSubTitVue title="其他信息"></formSubTitVue>
        </div> -->

        <div class="center">
          <el-button @click="close()">取消</el-button>
          <el-button type="primary" @click="submitForm('form')" v-loading="loading">提交</el-button>
        </div>
      </el-form>
      <!-- 弹出 -->

      <!-- 渠道选择 -->
      <qudaoDialog ref="qudaoDialog" @change="getSelectQudao"></qudaoDialog>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from "@/utils/auth";
import orderApi from "@/api/pickUp/order";

import gameListApi from "@/api/gameConfig/gameList";
import formSubTitVue from "@/views/tenantPages/components/formSubTit.vue";

import supplyConfigApi from "@/api/system/supplyConfig";

import qudaoDialog from "../../recycleManage/recycleOrders/qudaoDialog.vue";
import saomaUpload from "../../../../components/upload/saomaUpload.vue";
export default {
  name: "",
  components: { formSubTitVue, qudaoDialog,saomaUpload },
  data() {
    var priceRule = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入金额"));
      } else if (!this.priceReg.test(value)) {
        callback(new Error("请输入正确的金额"));
      } else {
        callback();
      }
    };
    var phoneCheck = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error("手机号格式不正确"));
      } else {
        callback();
      }
    };
    var idCardRule = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入身份证号"));
      } else if (!this.idCardReg.test(value)) {
        callback(new Error("请输入正确的身份证号"));
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false,
      loading: false,

      currentGame: "",
      gameList: [],
      idcardImg1: [],
      idcardImg2: [],
      yuangongList: [],
      qufuTree: [],
      qufuProps: {
        value: "fieldName",
        label: "fieldName",
        children: "childGameAttributes",
        expandTrigger: "hover",
      },
      isBaopei: false,

      type: [
        {
          name: "收入",
          value: 1,
        },
        {
          name: "支出",
          value: 2,
        },
      ],
      billTypeList: [],
      billTypeConfig: null, //自定义字段配置
      title: "创建销售单",
      isEdit: false,
      uploadImgUrl: "",
      imgShowList: [],
      newImages: [],
      imgFileList: [],
      // 表单参数
      form: {
        gameId: "",
        qufuIds: "",
        accountNumber: "",
        accountPassword: "",
        changeTel: "",
        saleAmount: "",
        actualAmount: "",
        supplyAmount: "",
        guaranteeAmount: "",
        saleUserId: "",
        guaranteeTenantName: "",
        supplyChannel: "", //供货商
        saleChannel: "",
        sellerName: "",
        salePay: "",
        guaranteePayStatus: "",
        shoukuanfang: "",
        shoukuanzhanghao: "",
        name: "",
        idCard: "",
        phoneNumber: "",
        adress: "",
        emblemIdcardImg: "",
        faceIdcardImg: "",
        remark: "",
        otherNo: "",
        changePhoneState: "",
        changePhoneImg: "",
        orderImg: "",
      },
      headers: {},
      rules: {
        gameId: [{ required: true, message: "请选择游戏", trigger: "change" }],
        qufuIds: [{ required: true, message: "请选择区服", trigger: "change" }],
        accountNumber: [
          { required: true, message: "请输入游戏账号", trigger: "change" },
        ],
        // accountPassword: [
        //   { required: true, message: "请输入游戏密码", trigger: "change" },
        // ],
        // changeTel: [
        //   { required: true, message: "请选择手机号", trigger: "change" },
        //   { validator: phoneCheck, trigger: "change" },
        // ],
        // actualAmount: [
        //   { required: true, message: "请输入价格", trigger: "change" },
        //   { validator: priceRule, trigger: "change" },
        // ],
        saleAmount: [
          { required: true, message: "请输入出售价", trigger: "change" },
          { validator: priceRule, trigger: "change" },
        ],
        supplyAmount: [
          { required: true, message: "请输入成本价", trigger: "change" },
          { validator: priceRule, trigger: "change" },
        ],
        guaranteeAmount: [
          { required: true, message: "请输入包赔费", trigger: "change" },
          { validator: priceRule, trigger: "change" },
        ],
        saleUserId: [{ required: true, message: "请选择", trigger: "change" }],
        guaranteeTenantName: [
          { required: true, message: "请选择", trigger: "change" },
        ],
        saleChannel: [{ required: true, message: "请选择", trigger: "change" }],
        sellerName: [{ required: true, message: "请填写", trigger: "change" }],
        salePay: [{ required: true, message: "请选择", trigger: "change" }],
        
        changePhoneState: [
          { required: true, message: "请选择", trigger: "change" },
        ],
        guaranteePayStatus: [
          { required: true, message: "请选择", trigger: "change" },
        ],
        // shoukuanfang: [
        //   { required: true, message: "请填写", trigger: "change" },
        // ],
        // shoukuanzhanghao: [
        //   { required: true, message: "请填写", trigger: "change" },
        // ],

        // name: [{ required: true, message: "请填写", trigger: "change" }],
        // idCard: [
        //   { required: true, message: "请填写", trigger: "change" },
        //   { validator: idCardRule, trigger: "change" },
        // ],
        // phoneNumber: [
        //   { required: true, message: "请填写", trigger: "change" },
        //   { validator: phoneCheck, trigger: "change" },
        // ],
        // adress: [{ required: true, message: "请填写", trigger: "change" }],
      },
    };
  },
  created() {
    this.headers = {
      Authorization: "Bearer " + getToken(),
    };
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo;
    },
    // shopInfo() {
    //   return this.$store.getters.shopInfo;
    // },
    allGameList() {
      return this.$store.getters.allGameList;
    },
  },
  methods: {
    // 打开弹窗
    open(flag, id) {
      // console.log("%c Line:265 🥃 id", "color:#3f7cff", id);
      this.isBaopei = false;
      this.getYuangongList();
      this.getGameList();

      this.newImages = [];
      this.imgShowList = [];
      this.imgFileList = [];

      this.dialogVisible = true;
      this.title = "创建销售订单";
      if (flag == "edit") {
        this.title = "修改销售订单";
        this.isEdit = true;
        this.handleUpdate(id);
      } else {
        this.isEdit = false;
      }
    },

    // 重置
    reset() {
      // this.form = {
      //   type: "",
      //   bookType: "",
      //   duifangmingcheng: "",
      //   duifangzhanghu: "",
      //   benfangmingcheng: "",
      //   benfangzhanghu: "",
      //   jine: "",
      //   jingbanren: "",
      //   fuheren: "",
      //   mingxi: "",
      //   beizhu: "",
      //   img: "",
      // };
      this.qufuTree = [];
      this.$refs.form.resetFields();
    },
    // 获取区服树结构
    getQufuTree(gameId) {
      this.qufuTree = [];
      let obj = {};
      obj.gameId = gameId || this.form.gameId;
      gameListApi.qufuTreeGetByGameId(obj).then((res) => {
        this.qufuTree = [...res.data];
      });
    },
    // 获取所有员工列表
    getYuangongList() {
      supplyConfigApi
        .getAllUserList({
          userNewType: 1,
        })
        .then((res) => {
          this.yuangongList = res.rows;
        });
    },
    // 游戏列表
    async getGameList() {
      let res = await gameListApi.getCustomGamelist();
      // ////console.log("%c Line:278 🍫 res", "color:#465975", res);
      this.gameList = res.data;
      if (this.gameList && this.gameList.length) {
      } else {
        this.gameList = this.allGameList;
      }
    },
    // 游戏选择改变
    gameChange(e) {
      if (this.form.qufu) {
        this.form.qufu = "";
      }
      this.currentGame = "";
      this.form.gameName = "";
      if (e) {
        this.getQufuTree();
        for (let i = 0; i < this.gameList.length; i++) {
          if (this.gameList[i].id == e) {
            this.form.gameName = this.gameList[i].name;
            this.currentGame = this.gameList[i];
          }
        }
      }
    },
    // 回收人 改变
    buyerChange(e) {
      if (e) {
        for (let i = 0; i < this.yuangongList.length; i++) {
          if (this.yuangongList[i].userId == e) {
            this.form.saleUserNickname = this.yuangongList[i].nickName;
          }
        }
      } else {
        this.form.saleUserNickname = "";
      }
    },
    // 区服改变
    qufuChange(e) {},
    // 价格改变  计算利润
    computedBuyerActualAmount() {
      const guaranteeAmount = Number(this.form.guaranteeAmount||0)
      if (this.form.saleAmount ) {
        this.form.platformAmount = this.form.saleAmount;
        const total =
          Number(this.form.saleAmount) + guaranteeAmount;
        this.form.actualAmount = Math.round(total * 100) / 100;
      }
      if (this.form.actualAmount && this.form.supplyAmount) {
        const profits =
          Number(this.form.actualAmount) - Number(this.form.supplyAmount);
        this.form.profits = Math.round(profits * 100) / 100;
      }
      this.$forceUpdate();
    },
    /**选择相关  start*/
    //  取消选中渠道
    delPhone(type) {
      if (type == "phone") {
        this.form.telid = "";
        this.form.isMyTel = "";
        this.form.changeTel = "";
      } else if (type == "guaranteeTenantName") {
        this.form.guaranteeTenantName = "";
      } else if (type == "saleChannel") {
        this.form.saleChannel = "";
      } else if (type == "supplyChannel") {
        this.form.supplyChannel = "";
      }

      this.$forceUpdate();
    },
    // 打开渠道哦选择
    openSelectQudao(type) {
      this.$refs.qudaoDialog.open(type);
    },
    // 渠道选择完成
    getSelectQudao(item) {
      if (item.type == 1) {
        // 包赔商
        this.form.guaranteeTenantName = item.name;
      } else if (item.type == 2) {
        // 平台渠道
        this.form.saleChannel = item.name;
      } else if (item.type == 3) {
        // 供货商
        this.form.supplyChannel = item.name;
      }
      this.$forceUpdate();
    },
    /**选择相关  end*/

    /** 查询详情进行回显 */
    handleUpdate(id) {
      orderApi.querySelfOrderById(id).then((res) => {
        let form = { ...res.data };
        if (form.img) {
          const arr = JSON.parse(form.img);
          if (arr.length) {
            this.imgShowList = arr;
            this.imgFileList = JSON.parse(JSON.stringify(arr));
          }
        }
        // 获取区服
        if (form.gameId) {
          this.getQufuTree(form.gameId);
        }

        // 处理区服
        form.qufuIds = form.qufu ? form.qufu.split("/") : "";

        // 处理收款信息
        if (form.collection) {
          const obj = JSON.parse(form.collection);
          form.shoukuanfang = obj.shoukuanfang;
          form.shoukuanzhanghao = obj.shoukuanzhanghao;
        }

        this.form = { ...form };
      });
    },
    submitForm(formName) {
      this.$refs["" + formName].validate((valid) => {
        if (valid) {
          // 拼接新上传的图片
          if (this.newImages && this.newImages.length) {
            let newArr = [];
            this.newImages.forEach((img) => {
              newArr.push({
                name: img.name,
                url: img.response.data.filePath,
              });
            });
            this.form.img = JSON.stringify(this.imgFileList.concat(newArr));
          } else {
            this.form.img = JSON.stringify(this.imgFileList);
          }

          // 处理收款信息
          let collection = {
            shoukuanfang: this.form.shoukuanfang,
            shoukuanzhanghao: this.form.shoukuanzhanghao,
          };
          this.form.collection = JSON.stringify(collection);

          // 处理区服
          let qufu =
            this.form.qufuIds && this.form.qufuIds.length
              ? this.form.qufuIds.join("/")
              : "";

          this.form.qufu = qufu;
          this.form.realAccountNumber = this.form.accountNumber;
          if (this.isEdit) {
            // // 编辑
            orderApi.editOrderBySelf(this.form).then((res) => {
              this.$message.success(res.msg);
              this.dialogVisible = false;
              this.$parent.getList();
            });
          } else {
            // 新增
            console.log(this.form);
            orderApi.addOrderBySelf(this.form).then((res) => {
              this.$message.success(res.msg);
              this.dialogVisible = false;
              this.$emit("addSuccess");
              // this.$parent.getList();
            });
          }
        } else {
          this.$alert("请填写完整！");
        }
      });
    },
    // 单张图片上传成功
    uploadSucccess(e, key) {
      this.form[key] = e;
    },
    // 其他图片扫码上传
    saomaEnd(e) {
      console.log("%c Line:590 🍎 e", "color:#6ec1c2", e);
      if (e && e.length) {
        this.imgFileList = this.imgFileList.concat(e);
        this.imgShowList = this.imgShowList.concat(e);
      }
    },
    // 详情图片上传成功
    handleUploadSuccess(res, file, fileList) {
      if (res.code == 200) {
        // 取得新上传的文件
        this.newImages = fileList.filter((t) => {
          return t.url.indexOf("blob:") > -1;
        });
      }
    },
    // 详情图片删除
    handleRemove(response, fileList, file) {
      const that = this;
      // 1.获取将要删除图片的临时路径
      const filePath = response.url;
      // 2.找到图片对应的索引值
      this.imgFileList.forEach(function (element, key) {
        if (element.url === filePath) {
          that.imgFileList.splice(key, 1); //回显的图片
        }
      });
      this.newImages.forEach(function (element, key) {
        if (element.url === filePath) {
          that.newImages.splice(key, 1); //新上传的图片
        }
      });
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url],
      });
    },
    uploadNumber(file, fileList) {
      //限制图片数量
      this.$modal.msgError("最多只能上传50张图片");
    },
    close() {
      this.dialogVisible = false;
    },
  },
};
</script>
<style scoped lang="css">
.center {
  text-align: center;
}

/deep/ .upload_img_box .el-form-item {
  width: 250px;
}
.phone-box{
  align-items: center;
}
.phone-box .name{
  white-space: nowrap;width: 84px;overflow: hidden;text-overflow: ellipsis;
}
</style>
